import {getHeaders, getList} from '@/api/general'

const getDefaultState = () => {
  return {
    headers: [],
    list: [],
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_HEADERS: (state, headers) => {
    state.headers = headers;
  },
  SET_LIST: (state, list) => {
    state.list = list;
  }
}

const actions = {
  getHeaders({ commit, state }) {
    return new Promise((resolve, reject) => {
      if(state.headers && state.headers.length > 0) {
        resolve(state.headers);
      } else {
        getHeaders().then(response => {
          const headers = response.data.items
          commit('SET_HEADERS', headers)
          resolve(headers)
        }).catch(error => {
          reject(error)
        })
      }
    })
  },
  getList({ commit, state }) {
    return new Promise((resolve, reject) => {
      if(state.list && state.list.length > 0) {
        resolve(state.list);
      } else {
        getList().then(response => {
          const list = response.data.items
          commit('SET_LIST', list)
          resolve(list)
        }).catch(error => {
          reject(error)
        })
      }
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

